const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const { userModel } = require('../model/db')
const { refreshAuthMiddleware } = require('../middlewares/auth')

// 刷新访问令牌
router.post('/refresh-token', refreshAuthMiddleware, async (req, res) => {
    const { refreshToken } = req.body
    const user = await userModel.findById(req.user.id).select('+refreshToken')

    // 验证刷新令牌是否匹配
    if (user.refreshToken !== refreshToken) {
        return res.status(401).send({ code: 401, msg: '无效刷新令牌' })
    }

    // 生成新的访问令牌
    const newAccessToken = jwt.sign(
        { id: user._id },
        process.env.ACCESS_TOKEN_SECRET,
        { expiresIn: '15m' }
    )

    res.send({
        code: 200,
        msg: '令牌刷新成功',
        accessToken: newAccessToken
    })
})

// 注销刷新令牌
router.post('/logout', authMiddleware, async (req, res) => {
    // 清除刷新令牌
    await userModel.findByIdAndUpdate(req.user.id, {
        refreshToken: null,
        refreshTokenExpires: null
    })

    res.send({ code: 200, msg: '注销成功' })
})

module.exports = router